let song, fft;
let particles = [];
let particleMax = 500;
let baseHue = 0;

function preload() {
  song = loadSound('https://example.com/your-music.mp3'); // 替换音乐URL
}

function setup() {
  createCanvas(800, 600);
  colorMode(HSB, 360);
  noStroke();

  fft = new p5.FFT();
  song.loop();

  // 创建控制按钮
  let btn = createButton('切换播放');
  btn.mousePressed(() => song.isPlaying() ? song.pause() : song.loop());
}

function draw() {
  background(0, 0.1);
  
  // 分析音频频谱
  let spectrum = fft.analyze();
  let bass = fft.getEnergy("bass");
  let treble = fft.getEnergy("treble");

  // 创建新粒子（喷泉爆发）
  if (bass > 200 && frameCount % 2 === 0) {
    for (let i = 0; i < map(bass, 0, 255, 5, 20); i++) {
      if (particles.length < particleMax) {
        particles.push(new Particle(
          width/2 + random(-20, 20),
          height,
          random(-2, 2),
          map(bass, 0, 255, -5, -15),
          treble
        ));
      }
    }
  }

  // 更新并显示粒子
  for (let i = particles.length - 1; i >= 0; i--) {
    particles[i].update();
    particles[i].show();
    if (particles[i].isDead()) {
      particles.splice(i, 1);
    }
  }

  // 颜色渐变
  baseHue = (baseHue + 0.5) % 360;
}

class Particle {
  constructor(x, y, vx, vy, energy) {
    this.pos = createVector(x, y);
    this.vel = createVector(vx, vy);
    this.acc = createVector(0, 0.2);
    this.lifespan = 255;
    this.size = map(energy, 0, 255, 2, 8);
    this.hue = (baseHue + random(-30, 30)) % 360;
  }

  update() {
    this.vel.add(this.acc);
    this.pos.add(this.vel);
    this.lifespan -= 3;
    
    // 添加空气阻力效果
    this.vel.mult(0.98);
  }

  show() {
    fill(this.hue, 200, 255, this.lifespan/255 * 100);
    ellipse(this.pos.x, this.pos.y, this.size);
    
    // 添加拖尾效果
    if (random() > 0.7) {
      fill(this.hue, 150, 200, this.lifespan/255 * 50);
      ellipse(
        this.pos.x + random(-5,5),
        this.pos.y + random(-5,5),
        this.size * 0.8
      );
    }
  }

  isDead() {
    return this.lifespan < 0 || this.pos.y > height + 50;
  }
}

// 点击屏幕重置
function mousePressed() {
  particles = [];
}